package com.wude.guild.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.akexorcist.roundcornerprogressbar.RoundCornerProgressBar;
import com.liji.imagezoom.util.ImageZoom;
import com.mc.developmentkit.utils.MCUtils;
import com.mc.developmentkit.utils.ToastUtil;
import com.mc.developmentkit.views.FilletImageView;
import com.umeng.analytics.MobclickAgent;
import com.wude.bean.AppInfo;
import com.wude.bean.ShareInfo;
import com.wude.bean.UserInfo;
import com.wude.guild.LoginActivity;
import com.wude.guild.R;
import com.wude.guild.ScreenshotsActivity;
import com.wude.guild.dialog.SharedDialog;
import com.wude.guild.manager.DownloadManager;
import com.wude.guild.manager.DownloadObserver;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.DbUtils;
import com.wude.tools.Utils;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 简介Fragment
 * Created by Administrator on 2017/3/24.
 */
@SuppressLint("HandlerLeak")
public class GameDetIntroductionFragment extends Fragment implements DownloadObserver {
    @BindView(R.id.shoucang)
    ImageView shoucang;
    @BindView(R.id.share)
    ImageView share;
    @BindView(R.id.progressbar)
    RoundCornerProgressBar progressbar;
    @BindView(R.id.zi_down)
    TextView ziDown;
    @BindView(R.id.down)
    FrameLayout down;
    @BindView(R.id.dibu)
    RelativeLayout dibu;
    @BindView(R.id.gameInfo_ImagesLayout)
    LinearLayout gameInfoImagesLayout;
    @BindView(R.id.gameInfo_HorizontalScrollView)
    HorizontalScrollView gameInfoHorizontalScrollView;
    @BindView(R.id.error_text)
    TextView errorText;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.jieshao)
    TextView jieshao;

    private String id;
    public static AppInfo appInfo;
    private DbManager db;
    private boolean an = true;
    private boolean del = true;
    private boolean suo = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_gamedet_jianjie, null);
        ButterKnife.bind(this, inflate);
        id = getArguments().getString("key");
        HashMap<String, String> map = new HashMap<>();
        map.put("game_id", id);
        UserInfo loginUser = Utils.getLoginUser();
        if (loginUser != null) {
            map.put("token", loginUser.token);
        }
        HttpCom.POST(handler, HttpCom.getGameDetUrl(), map, false);
        return inflate;
    }

    @OnClick({R.id.shoucang, R.id.share, R.id.down})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shoucang:
                Collection();
                break;
            case R.id.share:
                if (Utils.getLoginUser() != null) {
                    if (appInfo != null) {
                        Share();
                    }
                } else
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            case R.id.down:
                if (appInfo != null) {
                    xiazai();
                }
                break;
        }
    }

    /**
     * 点击下载按钮执行
     */
    public void xiazai() {
        AppInfo down1 = down(appInfo);
        switch (down1.btnStatus) {
            case DownloadManager.DOWNLOAD_NOT:
                if (suo) {
                    suo = false;
                    Utils.getDownLoadUrl(nhandler, down1.id);
                }
                break;
            case DownloadManager.DOWNLOAD_LOADING:
                PuseDownLoad(down1);
                break;
            case DownloadManager.DOWNLOAD_SUCCESS:
                InStall(down1);
                break;
            case DownloadManager.DOWNLOAD_FAILED:
                if (suo) {
                    suo = false;
                    Utils.getDownLoadUrl(nhandler, down1.id);
                }
                break;
            case DownloadManager.DOWNLOAD_INSTALL:
                Open(down1);
                break;
            case DownloadManager.DOWNLOAD_PAUSE:
                StartDownLoad(down1);
                break;
        }
    }

    /**
     * 获取Appinfo
     *
     * @param app
     * @return
     */
    public AppInfo down(AppInfo app) {
        try {
            if (db == null) {
                db = DbUtils.getDB();
            }
            AppInfo byId = db.findById(AppInfo.class, app.id);
            if (byId == null) {
                return app;
            } else {
                return byId;
            }
        } catch (DbException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据下载状态改变UI
     *
     * @param app
     */
    public void Status(AppInfo app) {
        switch (app.btnStatus) {
            case DownloadManager.DOWNLOAD_WAITING:
                int juhuang7 = x.app().getResources().getColor(R.color.juhuang);
                ziDown.setTextColor(juhuang7);
                ziDown.setText("等待");
                progressbar.setProgress(0);
                break;
            case DownloadManager.DOWNLOAD_NOT:
                int lan1 = x.app().getResources().getColor(R.color.zi_lan);
                int baise = x.app().getResources().getColor(R.color.white);
                ziDown.setText("下载(" + app.size + ")");
                progressbar.setProgressColor(lan1);
                progressbar.setProgress(100);
                ziDown.setTextColor(baise);
                break;
            case DownloadManager.DOWNLOAD_LOADING:
                int lan = x.app().getResources().getColor(R.color.zi_lan);
                int juhuang2 = x.app().getResources().getColor(R.color.juhuang);
                int progress = (int) (app.progress * 100f / app.zsize + 0.5f);
                progressbar.setProgress(progress);
                progressbar.setProgressColor(lan);
                ziDown.setText(progress + "%");
                ziDown.setTextColor(juhuang2);
                break;
            case DownloadManager.DOWNLOAD_SUCCESS:
                int lan3 = x.app().getResources().getColor(R.color.zi_lan);
                int bai = x.app().getResources().getColor(R.color.white);
                ziDown.setText("安装");
                ziDown.setTextColor(bai);
                progressbar.setProgress(100);
                progressbar.setProgressColor(lan3);
                if (an) {
                    an = false;
                    an();
                }
                break;
            case DownloadManager.DOWNLOAD_FAILED:
                int juhuang = x.app().getResources().getColor(R.color.juhuang);
                int bai5 = x.app().getResources().getColor(R.color.white);
                ziDown.setText("重试");
                ziDown.setTextColor(bai5);
                progressbar.setProgress(100);
                progressbar.setProgressColor(juhuang);
                break;
            case DownloadManager.DOWNLOAD_INSTALL:
                int lan4 = x.app().getResources().getColor(R.color.zi_lan);
                int bai1 = x.app().getResources().getColor(R.color.white);
                ziDown.setText("打开");
                ziDown.setTextColor(bai1);
                progressbar.setProgress(100);
                progressbar.setProgressColor(lan4);
                if (del) {
                    del = false;
                    an();
                }
                break;
            case DownloadManager.DOWNLOAD_PAUSE:
                int bai2 = x.app().getResources().getColor(R.color.white);
                int hui = x.app().getResources().getColor(R.color.ccc);
                ziDown.setText("继续");
                ziDown.setTextColor(bai2);
                progressbar.setProgress(100);
                progressbar.setProgressColor(hui);
                break;
        }
    }

    /**
     * 下载完成后是否删除安装包并且判断是否真的安装过了
     */
    public void an() {
        if (appInfo != null) {
            AppInfo down = down(appInfo);
            DownloadManager.getInstance().isInstall(down);
        }
    }

    /**
     * 分享
     */
    private void Share() {
        HashMap<String, String> map = new HashMap<>();
        map.put("game_id", appInfo.id + "");
        HttpCom.POST(khandler, HttpCom.getGameShareURL(), map, false);
    }

    /**
     * 收藏
     */
    private void Collection() {
        UserInfo loginUser = Utils.getLoginUser();
        if (loginUser != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("token", loginUser.token);
            map.put("game_id", id + "");
            if (appInfo != null) {
                switch (appInfo.Collection) {
                    case 1:
                        map.put("status", "2");
                        break;
                    case 2:
                        map.put("status", "1");
                        break;
                }
                HttpCom.POST(mhandler, HttpCom.getShouCangUrl(), map, false);
            }
        } else {
            getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }


    /**
     * 横向滑动的游戏截图
     *
     * @param appInfo
     */
    private void initHorizontalSorollView(final AppInfo appInfo) {
        try {
            for (int i = 0; i < appInfo.jietu.size(); i++) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-0x1, -0x1);
                FilletImageView img = new FilletImageView(x.app());
                params.height = Utils.dipToPx(getActivity(), 200.0f);
                params.width = Utils.dipToPx(getActivity(), 130.0f);
                if (i != 0) {
                    params.leftMargin = Utils.dipToPx(getActivity(), 8.0f);
                }
                img.setLayoutParams(params);
                img.setTag(Integer.valueOf(i));
                img.setScaleType(ImageView.ScaleType.FIT_XY);
                final String imgs = appInfo.jietu.get(i);
                MCUtils.fillImage(img, imgs);
                gameInfoImagesLayout.addView(img);
                final int finalI = i;
                img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        startActivity(new Intent(getActivity(), ScreenshotsActivity.class));
                        showImgs(finalI, appInfo.jietu);
                    }
                });
            }
        } catch (Exception e) {
            Log.e("空指针了", e.toString());
        }
    }

    private void showImgs(int position, List<String> imgUrls) {
        ImageZoom.show(getContext(), position, imgUrls);
    }


    /**
     * 游戏详情
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    appInfo = HttpUtils.DNSGameDel(msg.obj.toString());
                    if (appInfo != null) {
                        downinfo = down(appInfo);
                        Status(downinfo);
                        initHorizontalSorollView(appInfo);
                        appInfo.introduce = appInfo.introduce.replace("\r\n", "<br />");
                        appInfo.introduce = appInfo.introduce.replace(" ", " ");
                        jieshao.setText(Html.fromHtml(appInfo.introduce));
                        switch (appInfo.Collection) {
                            case 1:         //已收藏
                                shoucang.setBackgroundResource(R.mipmap.game_btn_collection_pre);
                                break;
                            case 2:         //未收藏
                                shoucang.setBackgroundResource(R.mipmap.game_btn_collection_nor);
                                break;
                        }
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };

    /**
     * 收藏
     */
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    boolean b = HttpUtils.DNSShou(msg.obj.toString());
                    if (b) {
                        switch (appInfo.Collection) {
                            case 1:         //已收藏
                                appInfo.Collection = 2;
                                shoucang.setBackgroundResource(R.mipmap.game_btn_collection_nor);
                                ToastUtil.showToast("取消了收藏");
                                break;
                            case 2:         //未收藏
                                appInfo.Collection = 1;
                                shoucang.setBackgroundResource(R.mipmap.game_btn_collection_pre);
                                ToastUtil.showToast("已成功收藏");
                                break;
                        }
                    }
                    break;
                case 2:

                    break;
            }
        }
    };


    public void StartDownLoad(AppInfo app) {
        DownloadManager.getInstance().down(app);
    }

    public void PuseDownLoad(AppInfo app) {
        DownloadManager.getInstance().pause(app);
    }

    public void InStall(AppInfo app) {
        DownloadManager.getInstance().install(app);
    }

    public void Open(AppInfo app) {
        DownloadManager.getInstance().open(app);
    }


    private AppInfo downinfo;
    /**
     * 获得下载链接
     */
    Handler nhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String url = HttpUtils.DNSdownUrl(msg.obj.toString());
                    if (url != null && !url.equals("")) {
                        downinfo = down(appInfo);
                        downinfo.url = url;
                        StartDownLoad(downinfo);
                        suo = true;
                    }
                    break;
                case 2:
                    if (msg.obj.toString().equals("java.net.SocketTimeoutException")) {
                        AppInfo down1 = down(appInfo);
                        Utils.getDownLoadUrl(handler, down1.id);
                    } else {
                        ToastUtil.showToast("网络异常");
                    }
                    break;
            }
        }
    };


    /**
     * 获取分享内容
     */

    private SharedDialog dialog;
    Handler khandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    ShareInfo bena = HttpUtils.DNSShare(msg.obj.toString());
                    if (bena != null) {
                        if (dialog == null) {
                            dialog = new SharedDialog(getContext(), bena, 2);
                            dialog.show();
                        } else if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }

                    } else {
                        ToastUtil.showToast("分享失败");
                    }
                    break;
                case 2:

                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 下载状态回调方法
     *
     * @param manager
     * @param info
     */
    @Override
    public void onDownloadStateChanged(DownloadManager manager, AppInfo info) {
        if (appInfo != null) {
            if (appInfo.id == info.id) {
                Status(info);
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        DownloadManager.getInstance().addObserver(this);
        MobclickAgent.onPageStart("GameDetIntroductionFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        DownloadManager.getInstance().deleteObserver(this);
        MobclickAgent.onPageEnd("GameDetIntroductionFragment");
    }
}
